package com.liunian.algorithmstudy.nums;

import java.util.Arrays;

public class ThreeSumClosest16 {

    public int threeSumClosest(int[] nums, int target) {
        int n = nums.length;
        int res = Integer.MAX_VALUE;
        Arrays.sort(nums);
        for (int i = 0; i < n - 2; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            int left = i + 1;
            int right = n - 1;
            while (left < right) {
                int sum = nums[i] + nums[left] + nums[right];
                if (sum == target) {
                    return sum;
                } else {
                    res = Math.abs(sum - target) < Math.abs(res - target) ? sum : res;
                    if (sum < target) {
                        while (left < right && nums[left] == nums[left + 1]) {
                            left++;
                        }
                        left++;
                    } else {
                        while (left < right && nums[right] == nums[right - 1]) {
                            right--;
                        }
                        right--;
                    }
                }
            }
        }
        return res;
    }

    public static void main(String[] args) {
        ThreeSumClosest16 closest = new ThreeSumClosest16();
        System.out.println(closest.threeSumClosest(new int[]{-4, 2, 2, 3, 3, 3}, 0));
    }

}
